<?php
/**
 * Created by PhpStorm.
 * User: tangsian
 * Date: 2020/12/18
 * Time: 16:30
 */

namespace App\Http\Services;


use App\Http\Model\Api\FinanceDiamondStream;
use App\Http\Model\Api\Friends;
use App\Http\Model\Api\IntimacyStream;
use App\Http\Model\Api\Room;
use App\Http\Model\Api\RoomDurationRecord;
use App\Http\Model\SoundByte;
use App\Http\Model\User;

class SoundByteServices extends CommonServices
{
    protected $soundByteModel;
    protected $userModel;
    protected $roomModel;
    protected $friendsModel;
    protected $financeDiamondModel;
    protected $intimacyStreamModel;
    protected $roomDurationModel;

    public function __construct()
    {
        $this->soundByteModel = new SoundByte();
        $this->userModel = new User();
        $this->roomModel = new Room();
        $this->friendsModel = new Friends();
        $this->financeDiamondModel = new FinanceDiamondStream();
        $this->intimacyStreamModel = new IntimacyStream();
        $this->roomDurationModel = new RoomDurationRecord();
    }

    ######### 声浪 ############

    public function soundByteFamilyList($page, $limit,$user_id)
    {
        $data = $this->soundByteModel->soundByteFamilyList($page, $limit);

        $result = [];

        if (!empty($data['list'])) {
            $familyIds = array_keys($data['list']);


            $familyUserId = $this->soundByteModel->getFamilyByUserId($user_id);
            if(!empty($familyUserId)){
                $familyIds[]= $familyUserId;
            }
            $familyInfoList = $this->roomModel->getFamilyInfoByIds($familyIds);
            $familyKeyList = array_column($familyInfoList, null, 'family_uid');

            $i = 1;
            $familyUserShowList =[];
            if(!empty($familyUserId)){
                $showIndex = $this->soundByteModel->soundByteFamilyRank($familyUserId);
                if(!empty($showIndex) || $showIndex===0){
                    $showIndex = $showIndex+1;
                }
                if($showIndex>50){
                    $showIndex = 0;
                }

                $familyUserShowList =[
                    'images' => $this->build_image($familyKeyList[$familyUserId]['family_image']),
                    'nickname' => $familyKeyList[$familyUserId]['family_name'],
                    'rank_level' => $showIndex,
                    'score' => ceil($this->soundByteModel->soundByteFamilyScore($familyUserId)),
                ];

            }

            $familyAdvancedList = $this->soundByteModel->getFamilyAdvancedList();
            foreach ($data['list'] as $key => $val) {
                $item = [
                    'images' => $this->build_image($familyKeyList[$key]['family_image']),
                    'nickname' => $familyKeyList[$key]['family_name'],
                    'rank_level' => $page * $limit + $i,
                    'score' => ceil($val),
                    'is_advanced' => 0,
                ];

                if (!empty($familyAdvancedList)) {
                    $item['is_advanced'] = 1;
                    if (in_array($key, $familyAdvancedList)) {
                        $item['is_advanced'] = 2;
                    }
                }

                //前三名带工会音浪前6用户列表
                if ($page == 0 && $i <= 3) {
                    $roomList = $this->soundByteModel->getFamilyRoomRank($key, 0, 6);
                    if (!empty($roomList['list'])) {
                        foreach ($roomList['list'] as $roomKey => $roomVal) {
                            $roomItem = $this->roomModel->getRoomInfo($roomKey);
                            $roomItem['image'] = $this->build_image($roomItem['image']);
                            $item['user_data_list'][] = $roomItem;
                        }
                    }

                }

                $result['rank_list'][] = $item;
                $i++;
            }



            $result['family_user_show_list']=$familyUserShowList;
            $result['total_count'] = $data['total_count'];
        }
        return $result;

    }

    public function build_image($image)
    {
        return [build_image($image)];
    }

    //获取个人在不同房间排行
    public function soundBytePersonalListByType($type, $userId, $page, $limit)
    {
        $info = $this->soundByteModel->soundBytePersonalListByType($type, $page, $limit);

        $timeStep = $this->soundByteModel->getTimeStep();
        $advancedList = [];
        if ($timeStep >= 1) {
            $advancedList = $this->soundByteModel->getPersonalTypeAdvancedList($type);
        }
        $data = $this->dealUserInfoRankData($info['list'], $userId, $page * $limit, $advancedList);
        if ((empty($data['my_rank_data']['rank_level']) || empty($data['my_rank_data']['score'])) && !empty($data['my_rank_data']['nickname'])) {
//            if ($timeStep <= 1) {
//                $timeArray = $this->soundByteModel->getTimeStepTimeArray($timeStep);
                $mySoundByteSendUserRank = $this->soundByteModel->soundBytePersonalRank($userId, $type);
                $mySoundByteSendUserScore = $this->soundByteModel->soundBytePersonalScore($userId, $type);
                $data['my_rank_data']['score'] = ceil($mySoundByteSendUserScore) ?? 0;
                if ($mySoundByteSendUserRank == null) {
                    $mySoundByteSendUserRank = 1000;
                }
                $data['my_rank_data']['rank_level'] = $mySoundByteSendUserRank < 50 ? $mySoundByteSendUserRank + 1 : 0;
//            }
        }
        $data['total_count'] = $info['total_count'];
        return $data;

    }

    ######### 聚贤庄 ############
    //获取聚贤庄排行（活动期间好友数量新增）
    public function getFriendsCountRank($userId)
    {
        //获取阶段积累数据
        $yuanInfo = $this->friendsModel->get_yuan_friends_count_rank();
        //获取本阶段数据
        $newInfo = $this->friendsModel->get_step_friends_count_rank();
        if (!empty($yuanInfo) && !empty($newInfo)) {
            foreach ($newInfo as $key => $value) {
                $yuanInfo[$key] += intval($value);
            }
        } elseif (empty($yuanInfo)) {
            $yuanInfo = $newInfo;
        }
        $data = $this->dealUserInfoRankData($yuanInfo, $userId);
        if (empty($data['my_rank_data']['rank_level']) && !empty($data['my_rank_data']['nickname'])) {
            $timeStep = $this->friendsModel->getTimeStep();
            if ($timeStep < 1) {
                $timeArray = $this->friendsModel->getTimeStepTimeArray($timeStep);
                $myUserFriendsRank = $this->friendsModel->getUserFriendsRank($userId, $timeArray['start_time'], $timeArray['end_time']);
                $data['my_rank_data']['score'] = $myUserFriendsRank[$userId] ?? 0;
            }
        }

        $data['total_count'] = count($data['rank_list']);
        return $data;
    }

    //排行数据处理
    public function dealUserInfoRankData($data, $userId, $offset = 0, $advancedList = [])
    {
        $newData = [
            'rank_list' => [],
            'my_rank_data' => []
        ];
        $userIds = array_keys($data);
        $userIds[] = intval($userId);

        $userInfoList = $this->userModel->get_users_by_ids($userIds);
        $userKeyList = array_column($userInfoList, null, 'user_id');

        $newData['my_rank_data'] = [
            'images' => $userKeyList[$userId]['images'],
            'nickname' => $userKeyList[$userId]['nickname'],
            'rank_level' => 0,
            'score' => 0
        ];
        $i = 1 + $offset;
        foreach ($data as $k => $val) {
            $item = [
                'images' => $userKeyList[$k]['images'],
                'nickname' => $userKeyList[$k]['nickname'],
                'rank_level' => $i,
                'score' => ceil($val),
                'is_advanced' => 0,
            ];

            if (!empty($advancedList)) {
                $item['is_advanced'] = 1;
                if (in_array($k, $advancedList)) {
                    $item['is_advanced'] = 2;
                }
            }

            $newData['rank_list'][] = $item;
            if ($k == $userId) {
                $newData['my_rank_data']['rank_level'] = $item['rank_level'];
                $newData['my_rank_data']['score'] = $item['score'];
            }
            $i++;
        }
        return $newData;
    }

    //设置聚贤庄排行（活动期间好友数量新增）
    public function setFriendsCountRank()
    {
        $timeStep = $this->friendsModel->getTimeStep();
        $timeArray = $this->friendsModel->getTimeStepTimeArray($timeStep);
        if (!empty($timeArray['start_time']) && !empty($timeArray['end_time'])) {
            $advancedFriendsList = $this->friendsModel->getAdvancedFriendsList();
            $limit = 50;
            if (count($advancedFriendsList) > 0) {
                $limit = count($advancedFriendsList);
            }
            return $this->friendsModel->set_friends_count_rank([], $limit, $timeArray['start_time'], $timeArray['end_time'], $advancedFriendsList);
        }
    }

    //设置暂停时间，并生成下一阶段所需数据
    public function setFriendsSuspendTime($num)
    {
        $checkResult = $this->friendsModel->checkIsInTimeArr();
        if (!$checkResult) {
            return false;
        }

        //获取阶段积累数据
        $yuanInfo = $this->friendsModel->get_yuan_friends_count_rank();
        //获取本阶段数据
        $newInfo = $this->friendsModel->get_step_friends_count_rank();
        if (!empty($yuanInfo) && !empty($newInfo)) {
            foreach ($newInfo as $key => $value) {
                $yuanInfo[$key] += intval($value);
            }
        } elseif (empty($yuanInfo)) {
            $yuanInfo = $newInfo;
        }

        arsort($yuanInfo);
        if ($num > 0) {
            $advancedUserIds = array_keys(array_slice($yuanInfo, 0, $num));
            $this->friendsModel->setAdvancedFriendsList($advancedUserIds);
        }

        $this->friendsModel->setInSuspendTimeData($yuanInfo);

    }

    ######### 神豪 ############
    //获取神豪排行版
    public function soundByteSendUserList($userId, $page, $limit)
    {
        $info = $this->soundByteModel->soundByteSendUserList($page, $limit);
        $timeStep = $this->financeDiamondModel->getTimeStep();
        $advancedList = [];
//        if ($timeStep >= 1) {
//            $advancedList =$this->soundByteModel->getPersonalTypeAdvancedList();
//        }

        $data = $this->dealUserInfoRankData($info['list'], $userId, $page * $limit, $advancedList);
        if ((empty($data['my_rank_data']['rank_level']) || empty($data['my_rank_data']['score'])) && !empty($data['my_rank_data']['nickname'])) {
            if ($timeStep <= 1) {
                $timeArray = $this->financeDiamondModel->getTimeStepTimeArray($timeStep);
                $mySoundByteSendUserRank = $this->soundByteModel->soundByteSendUserRank($userId);
                $mySoundByteSendUserScore = $this->soundByteModel->soundByteSendUserScore($userId);
                $data['my_rank_data']['score'] = $mySoundByteSendUserScore ?? 0;
                if ($mySoundByteSendUserRank == null) {
                    $mySoundByteSendUserRank = 1000;
                }
                $data['my_rank_data']['rank_level'] = $mySoundByteSendUserRank <= 100 ? $mySoundByteSendUserRank + 1 : 0;
            }
        }
        $data['total_count'] = $info['total_count'];
        return $data;
    }


//    //获取神豪排行（活动期间充值数量）
//    public function getDiamondCountRank($userId)
//    {
//        //获取阶段积累数据
//        $yuanInfo = $this->financeDiamondModel->get_yuan_diamond_count_rank();
//        //获取本阶段数据
//        $newInfo = $this->financeDiamondModel->get_step_diamond_count_rank();
//        if (!empty($yuanInfo) && !empty($newInfo)) {
//            foreach ($newInfo as $key => $value) {
//                $yuanInfo[$key] += intval($value);
//            }
//        } elseif (empty($yuanInfo)) {
//            $yuanInfo = $newInfo;
//        }
//
//        $data = $this->dealUserInfoRankData($yuanInfo, $userId);
//        if (empty($data['my_rank_data']['rank_level']) && !empty($data['my_rank_data']['nickname'])) {
//            $timeStep = $this->financeDiamondModel->getTimeStep();
//            if ($timeStep < 1){
//                $timeArray = $this->financeDiamondModel->getTimeStepTimeArray($timeStep);
//                $myUserFriendsRank = $this->financeDiamondModel->getUserDiamondRank($userId,$timeArray['start_time'],$timeArray['end_time']);
//                $data['my_rank_data']['score'] = $myUserFriendsRank[$userId] ?? 0;
//            }
//        }
//        $data['total_count'] = count($data['rank_list']);
//        return $data;
//    }
//
//
//    //设置神豪排行（活动期间充值数量）
//    public function setDiamondCountRank()
//    {
//        $timeStep = $this->financeDiamondModel->getTimeStep();
//        $timeArray = $this->financeDiamondModel->getTimeStepTimeArray($timeStep);
//        if (!empty($timeArray['start_time']) && !empty($timeArray['end_time'])) {
//            $advancedDiamondList = $this->financeDiamondModel->getAdvancedDiamondList();
//            $limit = 100;
//            if (count($advancedDiamondList) > 0) {
//                $limit = count($advancedDiamondList);
//            }
//            return $this->financeDiamondModel->set_diamond_count_rank(['diamond_type' => 4], $limit, $timeArray['start_time'], $timeArray['end_time'], $advancedDiamondList);
//        }
//    }
//
//    //设置暂停时间，并生成下一阶段所需数据
//    public function setDiamondSuspendTime($num)
//    {
//        $checkResult = $this->financeDiamondModel->checkIsInTimeArr();
//        if (!$checkResult) {
//            return false;
//        }
//
//        //获取阶段积累数据
//        $yuanInfo = $this->financeDiamondModel->get_yuan_diamond_count_rank();
//        //获取本阶段数据
//        $newInfo = $this->financeDiamondModel->get_step_diamond_count_rank();
//        if (!empty($yuanInfo) && !empty($newInfo)) {
//            foreach ($newInfo as $key => $value) {
//                $yuanInfo[$key] += intval($value);
//            }
//        } elseif (empty($yuanInfo)) {
//            $yuanInfo = $newInfo;
//        }
//
//        arsort($yuanInfo);
//        if ($num > 0) {
//            $advancedUserIds = array_keys(array_slice($yuanInfo, 0, $num));
//            $this->financeDiamondModel->setAdvancedDiamondList($advancedUserIds);
//        }
//
//        $this->financeDiamondModel->setInSuspendTimeData($yuanInfo);
//
//    }

    ######## 神雕侠侣 ##########

    //获取神雕侠侣排行（活动期间亲密值增长）
    public function getIntimacyCountRank($userId)
    {
        //获取阶段积累数据
        $yuanInfo = $this->intimacyStreamModel->get_yuan_intimacy_count_rank();
        //获取本阶段数据
        $newInfo = $this->intimacyStreamModel->get_step_intimacy_count_rank();
        if (!empty($yuanInfo) && !empty($newInfo)) {
            foreach ($newInfo as $key => $value) {
                $yuanInfo[$key] += intval($value);
            }
        } elseif (empty($yuanInfo)) {
            $yuanInfo = $newInfo;
        }

        $data = $this->dealUserInfoRankData($yuanInfo, $userId);
        if (empty($data['my_rank_data']['rank_level']) && !empty($data['my_rank_data']['nickname'])) {
            $timeStep = $this->intimacyStreamModel->getTimeStep();
            if ($timeStep < 1) {
                $timeArray = $this->intimacyStreamModel->getTimeStepTimeArray($timeStep);
                $myUserFriendsRank = $this->intimacyStreamModel->getUserIntimacyRank($userId, $timeArray['start_time'], $timeArray['end_time']);
                $data['my_rank_data']['score'] = $myUserFriendsRank[$userId] ?? 0;
            }
        }
        $data['total_count'] = count($data['rank_list']);
        return $data;
    }


    //设置神雕侠侣排行（活动期间亲密值增长）
    public function setIntimacyCountRank()
    {
        $timeStep = $this->intimacyStreamModel->getTimeStep();
        $timeArray = $this->intimacyStreamModel->getTimeStepTimeArray($timeStep);
        if (!empty($timeArray['start_time']) && !empty($timeArray['end_time'])) {
            $advancedDiamondList = $this->intimacyStreamModel->getAdvancedIntimacyList();
            $limit = 100;
            if (count($advancedDiamondList) > 0) {
                $limit = count($advancedDiamondList);
            }
            return $this->intimacyStreamModel->set_intimacy_count_rank([], $limit, $timeArray['start_time'], $timeArray['end_time'], $advancedDiamondList);
        }
    }

    //设置暂停时间，并生成下一阶段所需数据
    public function setIntimacySuspendTime($num)
    {
        $checkResult = $this->intimacyStreamModel->checkIsInTimeArr();
        if (!$checkResult) {
            return false;
        }

        //获取阶段积累数据
        $yuanInfo = $this->intimacyStreamModel->get_yuan_intimacy_count_rank();
        //获取本阶段数据
        $newInfo = $this->intimacyStreamModel->get_step_intimacy_count_rank();
        if (!empty($yuanInfo) && !empty($newInfo)) {
            foreach ($newInfo as $key => $value) {
                $yuanInfo[$key] += intval($value);
            }
        } elseif (empty($yuanInfo)) {
            $yuanInfo = $newInfo;
        }

        arsort($yuanInfo);
        if ($num > 0) {
            $advancedUserIds = array_keys(array_slice($yuanInfo, 0, $num));
            $this->intimacyStreamModel->setAdvancedIntimacyList($advancedUserIds);
        }

        $this->intimacyStreamModel->setInSuspendTimeData($yuanInfo);

    }

    ##########窝神########
    public function soundByteSmallHouseList($userId, $page, $limit)
    {
        $info = $this->soundByteModel->soundByteSmallHouseList($page, $limit);

        $timeStep = $this->soundByteModel->getTimeStep();
        $advancedList = [];
        if ($timeStep >= 1) {
            $advancedList = $this->soundByteModel->geSmallHouseAdvancedList();
        }
        $data = $this->dealUserInfoRankData($info['list'], $userId, $page * $limit, $advancedList);
        if ((empty($data['my_rank_data']['rank_level']) || empty($data['my_rank_data']['score'])) && !empty($data['my_rank_data']['nickname'])) {
//            if ($timeStep <= 1) {
                $timeArray = $this->soundByteModel->getTimeStepTimeArray($timeStep);
                $mySoundByteSmallHouseRank = $this->soundByteModel->soundByteSmallHouseRank($userId);
                $mySoundByteSmallHouseScore = $this->soundByteModel->soundByteSmallHouseScore($userId);
                $data['my_rank_data']['score'] = ceil($mySoundByteSmallHouseScore) ?? 0;
                if ($mySoundByteSmallHouseRank == null) {
                    $mySoundByteSmallHouseRank = 1000;
                }
                $data['my_rank_data']['rank_level'] = $mySoundByteSmallHouseRank <= 100 ? $mySoundByteSmallHouseRank + 1 : 0;
//            }
        }
        $data['total_count'] = $info['total_count'];
        return $data;
    }

    ######## 宅神 ##########

    //获取宅神排行（活动期间小窝时长）
    public function getRoomDurationCountRank($userId)
    {
        //获取阶段积累数据
        $yuanInfo = $this->roomDurationModel->get_yuan_room_duration_count_rank();
        //获取本阶段数据
        $newInfo = $this->roomDurationModel->get_step_room_duration_count_rank();
        if (!empty($yuanInfo) && !empty($newInfo)) {
            foreach ($newInfo as $key => $value) {
                $yuanInfo[$key] += intval($value);
            }
        } elseif (empty($yuanInfo)) {
            $yuanInfo = $newInfo;
        }

        $data = $this->dealUserInfoRankData($yuanInfo, $userId);
        if (empty($data['my_rank_data']['rank_level']) && !empty($data['my_rank_data']['nickname'])) {
            $timeStep = $this->roomDurationModel->getTimeStep();
            if ($timeStep < 1) {
                $timeArray = $this->roomDurationModel->getTimeStepTimeArray($timeStep);
                $myUserFriendsRank = $this->roomDurationModel->getUserRoomDurationRank($userId, $timeArray['start_time'], $timeArray['end_time']);
                $data['my_rank_data']['score'] = $myUserFriendsRank[$userId] ?? 0;
            }
        }
        $data['total_count'] = count($data['rank_list']);
        return $data;
    }


    //设置宅神排行（活动期间小窝时长）
    public function setRoomDurationCountRank()
    {
        $timeStep = $this->roomDurationModel->getTimeStep();
        $timeArray = $this->roomDurationModel->getTimeStepTimeArray($timeStep);
        if (!empty($timeArray['start_time']) && !empty($timeArray['end_time'])) {
            $advancedRoomDurationList = $this->roomDurationModel->getAdvancedRoomDurationList();
            $limit = 100;
            if (count($advancedRoomDurationList) > 0) {
                $limit = count($advancedRoomDurationList);
            }
            return $this->roomDurationModel->set_room_duration_count_rank([], $limit, $timeArray['start_time'], $timeArray['end_time'], $advancedRoomDurationList);
        }
    }

    //设置暂停时间，并生成下一阶段所需数据
    public function setRoomDurationSuspendTime($num)
    {
        $checkResult = $this->roomDurationModel->checkIsInTimeArr();
        if (!$checkResult) {
            return false;
        }

        //获取阶段积累数据
        $yuanInfo = $this->roomDurationModel->get_yuan_room_duration_count_rank();
        //获取本阶段数据
        $newInfo = $this->roomDurationModel->get_step_room_duration_count_rank();
        if (!empty($yuanInfo) && !empty($newInfo)) {
            foreach ($newInfo as $key => $value) {
                $yuanInfo[$key] += intval($value);
            }
        } elseif (empty($yuanInfo)) {
            $yuanInfo = $newInfo;
        }

        arsort($yuanInfo);
        if ($num > 0) {
            $advancedUserIds = array_keys(array_slice($yuanInfo, 0, $num));
            $this->roomDurationModel->setAdvancedRoomDurationList($advancedUserIds);
        }

        $this->roomDurationModel->setInSuspendTimeData($yuanInfo);

    }

}
